<!-- views/category/index.vue -->
<template>
  <div class="category-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="分类名称">
          <el-input v-model="queryParams.name" placeholder="请输入分类名称" clearable />
        </el-form-item>
        <el-form-item label="分类类型">
          <el-select v-model="queryParams.type" placeholder="请选择分类类型" style="width: 200px" clearable>
            <el-option label="爬虫分类" value="crawler" />
            <el-option label="文章分类" value="article" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 200px" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <div class="left">
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>新增分类
            </el-button>
            <el-button
                type="danger"
                :disabled="!selectedCategories.length"
                @click="handleBatchDelete"
            >
              批量删除
            </el-button>
          </div>
          <div class="right">
            <el-tag v-if="selectedCategories.length" type="info">
              已选择 {{ selectedCategories.length }} 项
            </el-tag>
          </div>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table
          v-loading="loading"
          :data="categoryList"
          row-key="id"
          :tree-props="{ children: 'children' }"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" :selectable="isSelectable" />
        <el-table-column prop="name" label="分类名称" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.name }}</span>
            <el-tag v-if="isBaseCategory(row)" size="small" type="warning">
              系统分类
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="code" label="分类编码" width="150" />
        <el-table-column prop="path" label="分类路径" show-overflow-tooltip />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                  link
                  type="primary"
                  :disabled="isBaseCategory(row)"
                  @click="handleUpdate(row)"
              >
                编辑
              </el-button>
              <el-button
                  link
                  type="primary"
                  @click="handleAddChild(row)"
              >
                添加子分类
              </el-button>
              <el-button
                  link
                  type="danger"
                  :disabled="isBaseCategory(row)"
                  @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分类编辑弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="上级分类" v-if="!form.isRoot">
          <el-cascader
              v-model="form.parentId"
              :options="categoryList"
              :props="{
              checkStrictly: true,
              label: 'name',
              value: 'id'
            }"
              placeholder="请选择上级分类"
              clearable
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入分类编码" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
              v-model="form.description"
              type="textarea"
              placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import {
  listCategory,
  addCategory,
  updateCategory,
  deleteCategory,
  batchDeleteCategory, updateCategorySort, updateCategoryStatus
} from '@/api/category'
import {Plus, Refresh} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
const formRef = ref(null)
// 基础分类编码列表
const BASE_CATEGORIES = ['SOCCER_ODD', 'FREE_SUPER_TIPS', 'ESPN']

// 是否是基础分类
const isBaseCategory = (row) => {
  return BASE_CATEGORIES.includes(row.code) ||
      row.code?.startsWith('ESPN_')
}

// 表格选择项是否可选
const isSelectable = (row) => {
  return !isBaseCategory(row)
}

// 查询参数
const queryParams = reactive({
  name: '',
  type: '',
  status: null
})

// 表格数据
const loading = ref(false)
const categoryList = ref([])
const selectedCategories = ref([])

// 获取分类列表
const getList = async () => {
  loading.value = true
  try {
    const res = await listCategory(queryParams)
    categoryList.value = res.data
  } finally {
    loading.value = false
  }
}

// 表单数据
const dialog = reactive({
  visible: false,
  title: '',
  type: 'add'  // add, update, addChild
})

const form = reactive({
  id: null,
  parentId: null,
  name: '',
  code: '',
  sort: 0,
  status: 1,
  description: '',
  isRoot: false
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '只能包含大写字母和下划线', trigger: 'blur' }
  ]
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()

  const submitData = { ...form }

  if (Array.isArray(submitData.parentId)) {
    submitData.parentId = submitData.parentId[0]
  }

  try {
    if (dialog.type === 'add' || dialog.type === 'addChild') {
      await addCategory(submitData)
    } else {
      await updateCategory(submitData)
    }

    ElMessage.success('操作成功')
    dialog.visible = false
    getList()
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedCategories.value.length) return

  try {
    await ElMessageBox.confirm('确定要删除选中的分类吗？')
    await batchDeleteCategory(selectedCategories.value.map(item => item.id))
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 查询
const handleQuery = () => {
  getList()
}

// 重置查询
const handleReset = () => {
  queryParams.name = ''
  queryParams.type = ''
  queryParams.status = null
  handleQuery()
}

// 表格多选
const handleSelectionChange = (selection) => {
  selectedCategories.value = selection
}

// 新增分类
const handleAdd = () => {
  dialog.type = 'add'
  dialog.title = '新增分类'
  dialog.visible = true
  form.isRoot = true
  resetForm()
}

// 编辑分类
const handleUpdate = (row) => {
  dialog.type = 'update'
  dialog.title = '编辑分类'
  dialog.visible = true
  form.isRoot = false
  Object.assign(form, row)
}

// 添加子分类
const handleAddChild = (row) => {
  dialog.type = 'addChild'
  dialog.title = '添加子分类'
  dialog.visible = true
  form.isRoot = false
  resetForm()
  form.parentId = row.id
  form.type = row.type
}

// 删除分类
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确认删除分类"${row.name}"吗？`)
    await deleteCategory(row.id)
    ElMessage.success('删除成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.parentId = null
  form.name = ''
  form.code = ''
  form.sort = 0
  form.status = 1
  form.description = ''
  form.type = 'crawler'  // 默认为爬虫分类
}

// // 加载分类选项
// const categoryOptions = ref([])
// const loadCategoryOptions = async () => {
//   try {
//     const res = await listCategory({ type: 'crawler' })
//     categoryOptions.value = res.data
//   } catch (error) {
//     ElMessage.error('获取分类列表失败')
//   }
// }

// 更新分类状态
const handleStatusChange = async (row) => {
  try {
    await updateCategoryStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    // 恢复原状态
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error(error.message || '状态更新失败')
  }
}

// 更新排序
const handleSortChange = async (row) => {
  try {
    await updateCategorySort(row.id, row.sort)
    ElMessage.success('排序更新成功')
    getList()  // 重新加载以保证顺序正确
  } catch (error) {
    ElMessage.error(error.message || '排序更新失败')
  }
}

// 在组件挂载时加载数据
onMounted(() => {
  getList()
  // loadCategoryOptions()
})

// 监听表单对话框关闭
watch(() => dialog.visible, (val) => {
  if (!val) {
    resetForm()
    if (formRef.value) {
      formRef.value.resetFields()
    }
  }
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-card {
  margin-bottom: 20px;
}
</style>